import model from '../model/file'
import nodeModel from '../model/node'
const { uploadFile: uploadFileModel, addFile } = model
import { findTargetNode } from '../util/tree'
import { getCatalogues } from "../model/catalogue";
import conf from "../config/conf";
import { delDir } from "../util/file";
import { deleteNode } from '../model/node'
import _ from 'lodash'

// 上传文件
export const uploadFile = async (req, res) => {
  // 获取上传文件列表
  const files = req.files
  if (files.length !== 2 ||
    !(files[0].originalname.endsWith('.html') && files[1].originalname.endsWith('.css') ||
      files[0].originalname.endsWith('.css') && files[1].originalname.endsWith('.html'))
  ) {
    return {
      data: false,
      message: '须同时上传两个文件，且两个文件分别为html、css文件！'
    }
  }
  // 获取mainId
  const mainId = req.body.mainId - 0
  // 获取树节点
  let tree = await getCatalogues()
  // 根据mainId，获取目标节点
  let target = findTargetNode({mainId, tree})
  // 如果上传文件所选择的节点是文件
  // 或 所选的节点是文件夹，但是这个文件夹下已有子文件夹
  // if (!target || (target.type === 2 || target.type === 1 && target.children.length && target.children.some(item => item.type === 1))) {
  if (!target || target.type === 2) {
    delDir({path: conf.uploadTmpDir, isDeleteSelf: false})
    return {
      data: false,
      message: '要上传到的目标节点不存在！'
    }
  }
  
  // 查看目标节点下有没有同名的文件
  let htmlFileName = _.find(req.files, file => file.originalname.endsWith('.html'))
  htmlFileName = htmlFileName && (htmlFileName.originalname)
  if (htmlFileName) {
    const repeatNode =_.find(target.children, item => item.label === htmlFileName)
    if (repeatNode) {
      await nodeModel.deleteNode({mainId: repeatNode.mainId - 0})
      // 删除后重新获取树节点
      // console.log(getCatalogues().then(res => console.log(123, res)))
      tree = await getCatalogues()
      // 根据mainId，获取目标节点
      target = findTargetNode({mainId, tree})
    }
  }
  
  // 上传文件
  let data = await uploadFileModel(req.files)
  // 处理结果 boolean
  const result = data.every(item => item.status)
  // 如果处理失败
  if (!result) {
    return {
      data: false,
      message: '上传失败！'
    }
  }
  
  // 更新json中的数据
  let resultData = await addFile({files: data, parentNode: target, mainId, tree})
  
  return resultData
}

